package com.silp.labs.endclass;



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreProtocolPNames;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


/**
 * @author silp
 *
 */
public class EndclassActivity extends Activity {
	protected static final String END_CLASS = "Silp";
	protected static final String LOG_TAG = "SILP";
	



	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		final SharedPreferences mSp = getSharedPreferences(END_CLASS,MODE_PRIVATE);
		final String strhost = mSp.getString("Hostname", "");
		final String struser = mSp.getString("User", "");
		final String strpass = mSp.getString("Pass", "");

		if(strhost==""){
			createcustomdialog().show();

		}

		Button mButton_login = (Button)findViewById(R.id.btn_login);
		mButton_login.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				Log.i(LOG_TAG, "On Click");
				if (strhost!="") {
					postLoginData(strhost, struser, strpass);
					
				} else {
					postLoginData(mSp.getString("Hostname", ""), mSp.getString("User", ""), mSp.getString("Pass", ""));
				}
				
			}
		});


	}

	public Builder createcustomdialog() {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		final View dialog_v =getLayoutInflater().inflate(R.layout.dialog_layout, null);
		alert.setView(dialog_v);
		alert.setTitle("Add new host");
		alert.setMessage("Provide information for new host");
		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int whichButton) {

				EditText inputhost = (EditText)dialog_v.findViewById(R.id.editText1);
				final EditText inputuser = (EditText)dialog_v.findViewById(R.id.editText2);
				final EditText inputpass = (EditText)dialog_v.findViewById(R.id.editText3);
				Editable host = inputhost.getText();
				Editable user = inputuser.getText();
				Editable pass = inputpass.getText();
				SharedPreferences mSp = getSharedPreferences(END_CLASS,MODE_PRIVATE);
				SharedPreferences.Editor editor = mSp.edit();
				editor.putString("Hostname", "http://"+host.toString());
				editor.putString("User", user.toString());
				editor.putString("Pass", pass.toString());
				editor.commit();
			}
		});

		alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {

			}
			
		});
		return alert;
	}

	public void postLoginData(String strUrl,String struser,String strpass) {
		
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(strUrl);
		try {

			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
			nameValuePairs.add(new BasicNameValuePair("action", "login"));
			nameValuePairs.add(new BasicNameValuePair("login_username", struser));
			nameValuePairs.add(new BasicNameValuePair("login_password", strpass));
			httppost.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE );
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			Log.i(LOG_TAG, "Execute HTTP Post Request");
			HttpResponse response = httpclient.execute(httppost);

			String strreponse = inputStreamToString(response.getEntity().getContent()).toString();
			Log.w("SILP", strreponse);
			int leng = strreponse.length();
			Log.i("SILP",""+leng);
			if (leng>=1500) {
				Log.i("SILP","Login Success");
				Toast.makeText(getApplicationContext(), "Login Success", 100).show();
				Intent mIntent = new Intent(EndclassActivity.this,Graphiew.class);
				mIntent.putExtra("html", strreponse);
				startActivity(mIntent);
				
			} else {
				Log.i("SILP","Login Failed");
				Toast.makeText(getApplicationContext(), "Login failed", 100).show();
				createcustomdialog().show();
				
				
				
			}

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

	private StringBuilder inputStreamToString(InputStream is) {
		String line = "";
		StringBuilder total = new StringBuilder();
		// Wrap a BufferedReader around the InputStream
		BufferedReader rd = new BufferedReader(new InputStreamReader(is));
		// Read response until the end
		try {
			while ((line = rd.readLine()) != null) { 
				total.append(line); 
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		// Return full string
		return total;
	}
}
